package com.member.mp.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.R;
import com.member.common.enums.DeleteEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.enums.StatusEnum;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.*;
import com.member.shop.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 【首页】控制器
 *
 * @author wangxin
 * @version 1.0
 * @date Mon Jul 03 22:06:51 CST 2024
 **/
@RestController
@Api(value = "首页接口", tags = {"首页接口"})
@RequestMapping("/wx/index")
public class IndexController extends SupperController {

    @Resource
    private ISysBizRecommendCategoryService recommendCategoryService;
    @Resource
    private ISysBizRecommendGoodsService sysBizRecommendGoodsService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;
    @Resource
    private ISysBizCarouselService sysBizCarouselService;
    @Resource
    private ISysBizJingangService sysBizJingangService;
    @Resource
    private ISysBizActivityService sysBizActivityService;
    @Resource
    private ISysBizGoodsService sysBizGoodsService;
    @Resource
    private ISysBizHotService sysBizHotService;

    /**
     * 获取首页banner
     *
     * @param type 类型（0：首页轮播 1：腰封广告）
     * @return banner列表
     */
    @GetMapping("/queryBanner")
    public R<List<SysBizCarousel>> queryBanner(@RequestParam(value = "type") Integer type) {
        LambdaQueryWrapper<SysBizCarousel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizCarousel::getTenantId, getTenantId());
        queryWrapper.eq(SysBizCarousel::getDisplayed, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.eq(SysBizCarousel::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        if (type != null) {
            queryWrapper.eq(SysBizCarousel::getType, type);
        }
        queryWrapper.orderByDesc(SysBizCarousel::getOrderNum);
        queryWrapper.orderByDesc(SysBizCarousel::getId);
        List<SysBizCarousel> sysBizCarousels = sysBizCarouselService.selectSysBizCarouselList(queryWrapper);
        if(Objects.equals(type, 0)){
            if (!CollectionUtils.isEmpty(sysBizCarousels) && sysBizCarousels.size() >= 6) {
                return R.ok(sysBizCarousels.subList(0, 6));
            }
        }else if(Objects.equals(type, 1)){
            if (!CollectionUtils.isEmpty(sysBizCarousels) && sysBizCarousels.size() >= 4) {
                return R.ok(sysBizCarousels.subList(0, 4));
            }
        }

        return R.ok(sysBizCarousels);
    }

    /**
     * 获取首页金刚区
     *
     * @param region 展示区域
     * @return 金刚区列表
     */
    @GetMapping("/queryJingang")
    public R<List<SysBizJingang>> queryJingang(@RequestParam(value = "region") Integer region) {

        LambdaQueryWrapper<SysBizJingang> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizJingang::getTenantId, getTenantId());
        queryWrapper.eq(SysBizJingang::getDisplayed, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.eq(SysBizJingang::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        if (region != null) {
            queryWrapper.eq(SysBizJingang::getRegion, region);
        }
        queryWrapper.orderByDesc(SysBizJingang::getOrderNum);
        queryWrapper.orderByDesc(SysBizJingang::getJingangId);
        List<SysBizJingang> sysBizJingangs = sysBizJingangService.selectSysBizJingangList(queryWrapper);
        if (!CollectionUtils.isEmpty(sysBizJingangs) && sysBizJingangs.size() >= 20) {
            return R.ok(sysBizJingangs.subList(0, 20));
        }
        return R.ok(sysBizJingangs);
    }

    /**
     * 获取推荐分类
     *
     * @param
     * @return 分类列表
     */
    @GetMapping("/queryRecommendCategory")
    public R<List<SysBizRecommendCategory>> queryRecommendCategory() {
        LambdaQueryWrapper<SysBizRecommendCategory> recommendWrapper = new LambdaQueryWrapper<>();

        Long tenantId = getTenantId();
        recommendWrapper.eq(SysBizRecommendCategory::getRecommendType, 0);
        recommendWrapper.eq(SysBizRecommendCategory::getTenantId, tenantId);
        recommendWrapper.eq(SysBizRecommendCategory::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        recommendWrapper.orderByDesc(SysBizRecommendCategory::getOrderNum);
        recommendWrapper.last(" limit 4 ");
        List<SysBizRecommendCategory> list = recommendCategoryService.list(recommendWrapper);

        return R.ok(list);

    }

    //根据分类获取商品
    @GetMapping("/queryGoodsByCategory/{id}")
    public R<List<SysBizGoodsSku>> queryGoodsByCategory(@PathVariable Long id) {

        List<SysBizRecommendGoods> sysBizRecommendGoods = sysBizRecommendGoodsService.selectSysBizRecommendGoodsList(new LambdaQueryWrapper<SysBizRecommendGoods>()
                .eq(SysBizRecommendGoods::getRecommendCategoryId, id)
                .orderByDesc(SysBizRecommendGoods::getOrderNum));

        if(!CollectionUtils.isEmpty(sysBizRecommendGoods)){
            List<Long> collect = sysBizRecommendGoods.stream().map(SysBizRecommendGoods::getGoodsId).collect(Collectors.toList());

            String idListString = collect.stream().map(String::valueOf).collect(Collectors.joining(","));
            List<SysBizGoodsSku> sysBizGoodsSkuList = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                    .in(SysBizGoodsSku::getId, collect)
                    .eq(SysBizGoodsSku::getStatus, 0L)
                    .last("ORDER BY FIELD(id, " + idListString + ")"));
            for (SysBizGoodsSku sysBizGoodsSku : sysBizGoodsSkuList) {
                Long goodsId = sysBizGoodsSku.getGoodsId();
                SysBizGoods sysBizGoods = sysBizGoodsService.selectSysBizGoodsById(goodsId);
                sysBizGoodsSku.setGoodsName(sysBizGoods.getName());
            }
            return R.ok(sysBizGoodsSkuList);
        }
        return R.ok();
    }

    /**
     * 获取首页活动（未完成）
     *
     * @return 活动列表
     */
    @GetMapping("/queryActivity")
    public R<List<SysBizActivity>> queryActivity() {
        LambdaQueryWrapper<SysBizActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizActivity::getDisplayed, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.eq(SysBizActivity::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        queryWrapper.eq(SysBizActivity::getTenantId, getTenantId());
        queryWrapper.ne(SysBizActivity::getStatus, 2);
        queryWrapper.orderByDesc(SysBizActivity::getId);
        List<SysBizActivity> selectSysBizActivityList = sysBizActivityService.selectSysBizActivityList(queryWrapper);
        if (!CollectionUtils.isEmpty(selectSysBizActivityList)) {
            return R.ok(selectSysBizActivityList.subList(0, 1));
        }
        return R.ok(selectSysBizActivityList);
    }

    /*热门搜索*/
    @GetMapping(value = "/recommend")
    public R<List<SysBizHot>> recommend() {
        try {
            // 根据ID查询系列管理信息
            LambdaQueryWrapper<SysBizHot> queryWrapper = new LambdaQueryWrapper<SysBizHot>();
            queryWrapper.eq(SysBizHot::getDeleted, DeleteEnum.NOT_DELETE.getKey());
            queryWrapper.eq(SysBizHot::getDisplayed, StatusEnum.DISABLE.getKey());
            queryWrapper.eq(SysBizHot::getSearchType,2);
            queryWrapper.eq(SysBizHot::getTenantId, getTenantId());
            List<SysBizHot> sysBizHots = sysBizHotService.selectSysBizHotList(queryWrapper);
            // 查询成功，返回封装了查询结果的响应对象
            return R.ok(sysBizHots);
        } catch (Exception e) {
            // 发生异常，返回错误信息
            return R.fail("系统错误，请稍后再试");
        }
    }

}
